package cn.ly.core.concurrent.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SellTicket implements Runnable{
	
	private Ticket ticket;
	
	private Lock lock = new ReentrantLock(true);//true为公平锁，
	
	public SellTicket(Ticket t){
		this.ticket = t;
	}

	@Override
	public void run() {
		while(this.ticket.num > 0 ){
			try{
				lock.lock();//必须保证一部分有可能引起线程同步问题的代码是原子性操作
				if(this.ticket.num > 0){
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName() + "正在出售" + this.ticket.num-- + "张票");
				}
			}finally{
				lock.unlock();
			}
		}
	}

}
